package com.comtime.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

public class Util {

	public static long formatTimeSringToLong(String strTime) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		Date date;
		try {
			date = formatter.parse(strTime);
			if (date == null) {
				return 0;
			} else {
				long currentTime = formatTimeDateToLong(date); // date类型转成long类型
				return currentTime;
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		; // String类型转成date类型
		return 0;

	}

	// date类型转换为long类型
	// date要转换的date类型的时�?
	public static long formatTimeDateToLong(Date date) {
		return date.getTime();
	}

	public static String formatTimeLongToString(long time) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		return sDateFormat.format(time);
	}

	// 获取年号
	public static int formatTimeYear(long time) {
		int n = 0;
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String str = sDateFormat.format(time);
		n = Integer.parseInt(str.substring(0, 4));

		return n;
	}

	// 获取当天几号
	public static int formatTimeDay(long time) {
		int n = 0;
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String str = sDateFormat.format(time);
		n = Integer.parseInt(str.substring(8, 10));

		return n;
	}

	// 获取当天几分
	public static int formatTimeM(long time) {
		int n = 0;
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String str = sDateFormat.format(time);
		n = Integer.parseInt(str.substring(14, 16));

		return n;
	}

	// 上午 11�?36
	public static String formatTime_morning_h_m(long time) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String formatTime = sDateFormat.format(time);

		Log.e("", " formatTime: " + formatTime);
		int h = Integer.valueOf(formatTime.substring(11, 13));
		String m = formatTime.substring(14, 16);

		if (h < 12) {
			formatTime = "上午 " + h + ":" + m;
		} else {
			if (h >= 13) {
				h = h - 12;
			}
			formatTime = "下午 " + h + ":" + m;
		}

		return formatTime;
	}

	// 2016�?1�?8�? 下午9:18
	public static String formatTimeStyle_2(long time) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String formatTime = sDateFormat.format(time);

		// Log.e("", " formatTime: "+formatTime) ;
		int h = Integer.valueOf(formatTime.substring(11, 13));
		String min = formatTime.substring(14, 16);

		int month = Integer.valueOf(formatTime.substring(5, 7));
		int day = Integer.valueOf(formatTime.substring(8, 10));
		formatTime = formatTime.substring(0, 4) + "年" + month + "月" + day
				+ "日";
		if (h < 12) {
			formatTime += "上午 " + h + ":" + min;
		} else {
			if (h >= 13) {
				h = h - 12;
			}
			formatTime += "下午 " + h + ":" + min;
		}

		return formatTime;
	}

	public static String formatTimeStyle_3(long time) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String formatTime = sDateFormat.format(time);

		// Log.e("", " formatTime: "+formatTime) ;
		int h = Integer.valueOf(formatTime.substring(11, 13));
		String min = formatTime.substring(14, 16);
		formatTime = h + ":" + min;

		return formatTime;
	}

	// 2016�?1�?8�? 下午9:18
	public static String formatTimeStyle_4(long time) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String formatTime = sDateFormat.format(time);

		// Log.e("", " formatTime: "+formatTime) ;
		int h = Integer.valueOf(formatTime.substring(11, 13));
		String min = formatTime.substring(14, 16);

		int month = Integer.valueOf(formatTime.substring(5, 7));
		int day = Integer.valueOf(formatTime.substring(8, 10));
		formatTime = formatTime.substring(0, 10);
		formatTime += " " + h + ":" + min;

		return formatTime;
	}

	// 小时
	public static int formatTimeByHH(long time) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String formatTime = sDateFormat.format(time);

		// Log.e("", " formatTime: "+formatTime) ;
		int h = Integer.valueOf(formatTime.substring(11, 13));

		return h;
	}

	public static String formatTimeMD(long time) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat("MM-dd");
		String formatTime = sDateFormat.format(time);

		return formatTime;
	}

	public static String formatTimeD(long time) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat("dd");
		String formatTime = sDateFormat.format(time);

		return formatTime;
	}

	public static String formatTimeYMD(long time) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String formatTime = sDateFormat.format(time);

		return formatTime;
	}

	public static String formatTimeYM(long time) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy年MM日");
		String formatTime = sDateFormat.format(time);

		return formatTime;
	}

	public static String formatTimeMD2(long time) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat("MM月dd日");
		String formatTime = sDateFormat.format(time);
		return formatTime;
	}

	public static String formatTimeMDHM(long time) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String formatTime = sDateFormat.format(time);

		int h = Integer.valueOf(formatTime.substring(11, 13));
		String min = formatTime.substring(14, 16);

		int month = Integer.valueOf(formatTime.substring(5, 7));
		int day = Integer.valueOf(formatTime.substring(8, 10));
		formatTime = month + "�?" + day + "�?";

		formatTime += +h + ":" + min;

		return formatTime;
	}

	public static String getCurrentTime(String format) {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
		String currentTime = sdf.format(date);
		return currentTime;
	}

	public static String getCurrentTime() {
		return getCurrentTime("yyyy-MM-dd  HH:mm:ss");
	}

	
	/**
	 * 验证手机格式
	 */
	public static boolean isMobileNO(String mobiles) {
		/*
		 * 移动�?134�?135�?136�?137�?138�?139�?150�?151�?157(TD)�?158�?159�?187�?188
		 * 联�?�：130�?131�?132�?152�?155�?156�?185�?186
		 * 电信�?133�?153�?180�?189、（1349卫�?�）
		 * 总结起来就是第一位必定为1，第二位必定�?3�?5�?8，其他位置的可以�?0-9
		 */
		String telRegex = "[1][34578]\\d{9}";// "[1]"代表�?1位为数字1�?"[3458]"代表第二位可以为3�?4�?5�?8中的�?个，"\\d{9}"代表后面是可以是0�?9的数字，�?9位�??
		if (TextUtils.isEmpty(mobiles)) {
			return false;
		} else
			return mobiles.matches(telRegex);
	}

	/**
	 * 有网没网
	 * 
	 * @param context
	 * @return
	 */
	public static boolean hasNetwork(Context context) {
		if (isWifiConnected(context)) {

			return true;
		}
		if (isMobileConnected(context)) {

			return true;
		}
		return false;
	}

	public static boolean isWifiConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mWiFiNetworkInfo = mConnectivityManager
					.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			if (mWiFiNetworkInfo != null) {
				return mWiFiNetworkInfo.isConnected();
			}
		}
		return false;
	}

	public static boolean isMobileConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mMobileNetworkInfo = mConnectivityManager
					.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			if (mMobileNetworkInfo != null) {
				return mMobileNetworkInfo.isConnected();
			}
		}
		return false;
	}

	/**
	 * 软件版本�?
	 * 
	 * @param context
	 * @return
	 */
	public static String getAppVersionName(Context context) {
		String versionName = "";
		try {
			// Get the package info
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;
			if (TextUtils.isEmpty(versionName)) {
				return "";
			}
		} catch (Exception e) {
			// Log.e(THIS_FILE, "Exception", e);
		}
		return versionName;
	}
	public static int getAppVersionCode(Context context) {
		int versionCode = 0;
		try {
			// Get the package info
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionCode = pi.versionCode;
			if (versionCode != 0) {
				return versionCode;
			}
		} catch (Exception e) {
			// Log.e(THIS_FILE, "Exception", e);
		}
		return 0;
	}
	/**
	 * �?测sdk
	 * 
	 * @return
	 */
	public static boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	public static double getOne(double b) {
		double b2 = (double) (Math.round(b * 10)) / 10;
		return b2;
	}

	/**
	 * is samsung
	 * 
	 * @return
	 */
	public static boolean CheckIsSamsung() {
		String brand = android.os.Build.BRAND;
		if (brand.toLowerCase().equals("samsung")) {
			return true;
		}
		return false;
	}

	/**
	 * 摄氏度和华氏度换算（ 华氏度 = 32 + 摄氏度 × 1.8,摄氏度 = (华氏度 - 32) ÷ 1.8）
	 */
	public static double centigradeToFahrenheit(double b) {

		return getOne(32 + b * 1.8);
	}

	public static double fahrenheitToCentigrade(double b) {

		return getOne((b - 32) / 1.8);
	}

	/**
	 * phone deviceid
	 */
	public static String getPhoneID(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String tmDevice = "" + tm.getDeviceId();
		return tmDevice;

	}

	public static boolean isAppOnForeground(Context context) {
		String packageName = null;
		try {
			packageName = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).packageName;
			// Log.e("package", "packageName"+packageName);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
		if (tasksInfo.size() > 0) {
			if (packageName.equals(tasksInfo.get(0).topActivity
					.getPackageName())) {

				return true;
			}
		}
		return false;
	}

	public static String getTime(int n) {

		return String.format("%02d", n);

	}

	public static ArrayList<String> bubbleSort(ArrayList<String> args) {// 冒泡排序算法
		for (int i = 0; i < args.size() - 1; i++) {
			for (int j = i + 1; j < args.size(); j++) {
				if (Integer.parseInt(args.get(i)) > Integer.parseInt(args
						.get(j))) {
					String temp = args.get(i);
					args.set(i, args.get(j));
					args.set(j, temp);

				}
			}
		}
		return args;
	}
	
	/**
	 * 闰年判断
	 */
	public static boolean checkYearIsLeap(int year){
        if (year % 4 == 0 && year % 100!=0||year%400==0) {  
            return true;
              
        }  else{
        	return false;
        }
	}
	
	public static int getMonthDays(int year ,int month){
		boolean b_leap=checkYearIsLeap(year);
		if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){
			return 31;
		}else if(month==4||month==6||month==9||month==11){
			return 30;
		}else {
			if(b_leap){
				return 29;
			}else{
				return 28;
			}
		}
		
	}

	// byte数组转string
	private final static byte[] hex = "0123456789ABCDEF".getBytes();
	public static String Bytes2HexString(byte[] b) {
		byte[] buff = new byte[2 * b.length];
		for (int i = 0; i < b.length; i++) {
			buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
			buff[2 * i + 1] = hex[b[i] & 0x0f];
		}
		return new String(buff);
	}
	
	public static String byte2String(byte[] buff) {
		StringBuffer sbuf = new StringBuffer();
		for (int i = 0; i < buff.length; i++) {
			int tmp = buff[i] & 0XFF;
			String str = Integer.toHexString(tmp);
			if (str.length() == 1) {
				sbuf.append("0" + str);
			} else {
				sbuf.append(str);
			}

		}
		return sbuf.toString();
	}
	
	//log
	private static void ShowLog(String str){
		if(MyConfig.ShowLog){
		Log.e("tag", str);
		}
	}
	
	/**
	 * string 转byte数组
	 * 
	 * @param str
	 * @return
	 */
	public static byte[] stringToBytes(String str) {
		str = str.toUpperCase();

		byte[] bytes = new byte[str.length() / 2];
		for (int i = 0; i < str.length() - 1; i += 2) {
			String subString = str.substring(i, i + 2);
			int value = 0;
			for (int j = 0; j < 2; j++) {
				switch (subString.charAt(j)) {
				case '0':
					if (j == 0) {
						value = value + 16 * 0;
					} else {
						value = value + 0;
					}
					break;
				case '1':
					if (j == 0) {
						value = value + 16 * 1;
					} else {
						value = value + 1;
					}
					break;

				case '2':
					if (j == 0) {
						value = value + 16 * 2;
					} else {
						value = value + 2;
					}
					break;

				case '3':
					if (j == 0) {
						value = value + 16 * 3;
					} else {
						value = value + 3;
					}
					break;

				case '4':
					if (j == 0) {
						value = value + 16 * 4;
					} else {
						value = value + 4;
					}
					break;

				case '5':
					if (j == 0) {
						value = value + 16 * 5;
					} else {
						value = value + 5;
					}
					break;

				case '6':
					if (j == 0) {
						value = value + 16 * 6;
					} else {
						value = value + 6;
					}
					break;

				case '7':
					if (j == 0) {
						value = value + 16 * 7;
					} else {
						value = value + 7;
					}
					break;

				case '8':
					if (j == 0) {
						value = value + 16 * 8;
					} else {
						value = value + 8;
					}
					break;

				case '9':
					if (j == 0) {
						value = value + 16 * 9;
					} else {
						value = value + 9;
					}
					break;

				case 'A':
					if (j == 0) {
						value = value + 16 * 10;
					} else {
						value = value + 10;
					}
					break;
				case 'B':
					if (j == 0) {
						value = value + 16 * 11;
					} else {
						value = value + 11;
					}
					break;
				case 'C':
					if (j == 0) {
						value = value + 16 * 12;
					} else {
						value = value + 12;
					}
					break;
				case 'D':
					if (j == 0) {
						value = value + 16 * 13;
					} else {
						value = value + 13;
					}
					break;
				case 'E':
					if (j == 0) {
						value = value + 16 * 14;
					} else {
						value = value + 14;
					}
					break;
				case 'F':
					if (j == 0) {
						value = value + 16 * 15;
					} else {
						value = value + 15;
					}
					break;
				default:
					break;
				}
			}
			bytes[i / 2] = (byte) value;
		}

		return bytes;
	}
	
	
	/**
	 * 16进制string 转byte数组
	 * 
	 * @param str
	 * @return
	 */
	public static byte[] stringToBytes2(String str) {
		str = str.toUpperCase();

		byte[] bytes = new byte[str.length() / 2];
		for (int i = 0; i < str.length() - 1; i += 2) {
			String subString = str.substring(i, i + 2);
			int value = 0;
			for (int j = 0; j < 2; j++) {
				switch (subString.charAt(j)) {
				case '0':
					if (j == 0) {
						value = value + 16 * 0;
					} else {
						value = value + 0;
					}
					break;
				case '1':
					if (j == 0) {
						value = value + 16 * 1;
					} else {
						value = value + 1;
					}
					break;

				case '2':
					if (j == 0) {
						value = value + 16 * 2;
					} else {
						value = value + 2;
					}
					break;

				case '3':
					if (j == 0) {
						value = value + 16 * 3;
					} else {
						value = value + 3;
					}
					break;

				case '4':
					if (j == 0) {
						value = value + 16 * 4;
					} else {
						value = value + 4;
					}
					break;

				case '5':
					if (j == 0) {
						value = value + 16 * 5;
					} else {
						value = value + 5;
					}
					break;

				case '6':
					if (j == 0) {
						value = value + 16 * 6;
					} else {
						value = value + 6;
					}
					break;

				case '7':
					if (j == 0) {
						value = value + 16 * 7;
					} else {
						value = value + 7;
					}
					break;

				case '8':
					if (j == 0) {
						value = value + 16 * 8;
					} else {
						value = value + 8;
					}
					break;

				case '9':
					if (j == 0) {
						value = value + 16 * 9;
					} else {
						value = value + 9;
					}
					break;

				case 'A':
					if (j == 0) {
						value = value + 16 * 10;
					} else {
						value = value + 10;
					}
					break;
				case 'B':
					if (j == 0) {
						value = value + 16 * 11;
					} else {
						value = value + 11;
					}
					break;
				case 'C':
					if (j == 0) {
						value = value + 16 * 12;
					} else {
						value = value + 12;
					}
					break;
				case 'D':
					if (j == 0) {
						value = value + 16 * 13;
					} else {
						value = value + 13;
					}
					break;
				case 'E':
					if (j == 0) {
						value = value + 16 * 14;
					} else {
						value = value + 14;
					}
					break;
				case 'F':
					if (j == 0) {
						value = value + 16 * 15;
					} else {
						value = value + 15;
					}
					break;
				default:
					break;
				}
			}
			bytes[i / 2] = (byte) value;
		}

		return bytes;
	}
	/**
	 * string 转成16位后补成8位
	 * @param str
	 * @return
	 */
	
	public static String stringTo16(String str){
		String string = String.format("%x", Long.parseLong(str)).toUpperCase();
		
		if(string.length()<8){
			StringBuffer buf = new StringBuffer();
			int num=8 - string.length();
			Log.e("tag", "wwwwwwwwwwww----num:"+num);
			for (int i = 0; i<num ; i++) {
				buf.append("0");
				Log.e("tag", "wwwwwwwwwwww:"+i);
			}
			string = buf.toString() + string;
			Log.e("tag", "wwwwwwwwwwww:"+string);
		}
		return string;
	}
	
	public static byte[] loadAssetsFile(Context context, String filePath) {
		LogUtils.e("TAG", "loadAssetsFile :"+filePath);
		byte[] bytes = null ;
		InputStream stream;
		try {
			stream = context.getAssets().open(filePath);
			bytes = new byte[stream.available()];
			stream.read(bytes, 0, bytes.length);
			stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bytes;
	}
	
	public static byte[] loadFile(Context context, String filePath) {
		LogUtils.e("TAG", "loadFile :"+filePath);
		byte[] bytes = null ;
		InputStream stream;
		try {
			stream=new FileInputStream(filePath);
			bytes = new byte[stream.available()];
			stream.read(bytes, 0, bytes.length);
			stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bytes;
	}
	

	public static String getFirmwarePath(float version) {
		return getPath(Environment.getExternalStorageDirectory() + "/"
				+ "smartkilimanjaro/firmware/"+version+"/");
	}
	public static String getPath(String path) {
		File f = new File(path);
		if (!f.exists()) {
			f.mkdirs();
		}
		return f.getAbsolutePath();
	}
}
